package com.papper.common.service.sys;

import com.google.common.collect.Lists;
import com.papper.common.bean.sys.SysGroup;
import com.papper.common.bean.sys.SysUser;
import com.papper.common.mapper.sys.SysGroupMapper;
import com.papper.common.service.ServiceImpl;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service("sysGroupService")
public class SysGroupService extends ServiceImpl<SysGroupMapper, SysGroup> {

	@Resource
	SysUserService  sysUserService;
	@Resource
	SysLimitService sysLimitService;

	public List<SysGroup> findByUserId(String systemId, String userId) {
		Example example = new Example(SysGroup.class);
		example.createCriteria().andEqualTo("systemId", systemId).andEqualTo("userId", userId);
		return find(example);
	}

	public List<SysGroup> fingByUserIds(String userIds) {
		String[]     userIdList = userIds.split(",");
		List<String> idList     = Lists.newArrayList();
		idList.addAll(Arrays.asList(userIdList));
		Example example = new Example(SysGroup.class);
		example.createCriteria().andIn("userId", idList);
		return find(example);

	}

	public List<SysGroup> findFamily(String family) {
		Example example = new Example(SysGroup.class);
		example.createCriteria().andLike("upFamily", "%" + family + "%");
		return find(example);
	}

	public void matchFamily(SysGroup sysGroup) {
		SysGroup parent = findById(sysGroup.getUpId());
		String   family;
		if (parent != null) {
			family = parent.getUpFamily() + "," + sysGroup.getId();
		} else {
			family = "0," + sysGroup.getId();
		}

		SysGroup upd = new SysGroup();
		upd.setId(sysGroup.getId());
		upd.setUpFamily(family);
		update(upd);

		sysGroup.setUpFamily(family);
	}

	public void deleteSysGroupById(Long id) {
		//删除组用户成员
		List<SysUser> users = sysUserService.findByGroupId(id);
		if (users != null) {
			for (SysUser o : users) {
				sysUserService.deleteUserTree(o.getId(), o.getFamily());
			}
		}
		// 删除当前组
		deleteById(id);
		//删除组权限信息
		sysLimitService.delLimitedByGroupIds(id.toString());
	}
}